<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jquery ajax json</title>
    <!--   引入jQuery -->
    <script src="https://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <style>
        .container {
            width: 100%;
        }

    </style>
    <script>
        $(function() {
          $("#btn").click(function (){
            let fields = $("#form1").serializeArray();
            var obj = {}; //声明一个对象
            //console.log(typeof fields);// Firebug输出
            //console.log(Array.isArray(fields));
            //console.log(fields);// Firebug输出
            $.each(fields, function (i, field) {
              obj[field.name] = field.value; //通过变量，将属性值，属性一起放到对象中
            });
            //console.log(obj)
            //console.log(JSON.stringify(obj))
            $.ajax({
              type: "post",
              url: "/person/json/data",
              async: true,
              contentType: 'application/json',
              dataType: 'JSON',
              data: JSON.stringify(obj),//将对象转为json字符串
              success: function(obj) { // 返回的是对象
                console.log('success');
                console.log(JSON.stringify(obj))
                console.log(obj)
              },
              error:function(err){
                console.log(err)
              }
            });
          })
        });
    </script>
</head>
<body>
<div class="container">
    <form id="form1">
        <div class="mb-3">
            <label class="form-label">用户名</label>
            <input type="text" name="name" class="form-control"  value="张老三" aria-describedby="emailHelp">
            <div id="emailHelp"class="form-text">输入用户名.</div>
        </div>
        <div class="mb-3">
            <label for="exampleInputPassword1" class="form-label">用户年龄</label>
            <input type="text" name="age" class="form-control" value="19" id="exampleInputPassword1">
        </div>
        <button type="button" id="btn" class="btn btn-primary">Submit</button>
    </form>

    <!--   引入bootstrap -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet"/>
</div>
</body>
</html>
